{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "t09eeeR5prIJ"
      },
      "source": [
        "##### Copyright 2018 The TensorFlow Authors."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "GCCk8_dHpuNf"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "hcD2nPQvPOFM"
      },
      "source": [
        "# Text generation using an RNN"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "joH3UQjMohtX"
      },
      "source": [
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "<td>\n",
        "  <a target=\"_blank\"  href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/r1/tutorials/sequences/text_generation.ipynb\">\n",
        "    <img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
        "</td>\n",
        "<td>\n",
        "<a target=\"_blank\"  href=\"https://github.com/tensorflow/docs/blob/master/site/en/r1/tutorials/sequences/text_generation.ipynb\"><img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
        "</td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "joH3UQjMohtX"
      },
      "source": [
        "> Note: This is an archived TF1 notebook. These are configured\n",
        "to run in TF2's \n",
        "[compatbility mode](https://www.tensorflow.org/guide/migrate)\n",
        "but will run in TF1 as well. To use TF1 in Colab, use the\n",
        "[%tensorflow_version 1.x](https://colab.research.google.com/notebooks/tensorflow_version.ipynb)\n",
        "magic."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BwpJ5IffzRG6"
      },
      "source": [
        "This tutorial demonstrates how to generate text using a character-based RNN. We will work with a dataset of Shakespeare's writing from Andrej Karpathy's [The Unreasonable Effectiveness of Recurrent Neural Networks](http://karpathy.github.io/2015/05/21/rnn-effectiveness/). Given a sequence of characters from this data (\"Shakespear\"), train a model to predict the next character in the sequence (\"e\"). Longer sequences of text can be generated by calling the model repeatedly.\n",
        "\n",
        "Note: Enable GPU acceleration to execute this notebook faster. In Colab: *Runtime > Change runtime type > Hardware acclerator > GPU*. If running locally make sure TensorFlow version >= 1.11.\n",
        "\n",
        "This tutorial includes runnable code implemented using [tf.keras](https://www.tensorflow.org/programmers_guide/keras) and [eager execution](https://www.tensorflow.org/programmers_guide/eager). The following is sample output when the model in this tutorial trained for 30 epochs, and started with the string \"Q\":\n",
        "\n",
        "<pre>\n",
        "QUEENE:\n",
        "I had thought thou hadst a Roman; for the oracle,\n",
        "Thus by All bids the man against the word,\n",
        "Which are so weak of care, by old care done;\n",
        "Your children were in your holy love,\n",
        "And the precipitation through the bleeding throne.\n",
        "\n",
        "BISHOP OF ELY:\n",
        "Marry, and will, my lord, to weep in such a one were prettiest;\n",
        "Yet now I was adopted heir\n",
        "Of the world's lamentable day,\n",
        "To watch the next way with his father with his face?\n",
        "\n",
        "ESCALUS:\n",
        "The cause why then we are all resolved more sons.\n",
        "\n",
        "VOLUMNIA:\n",
        "O, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, it is no sin it should be dead,\n",
        "And love and pale as any will to that word.\n",
        "\n",
        "QUEEN ELIZABETH:\n",
        "But how long have I heard the soul for this world,\n",
        "And show his hands of life be proved to stand.\n",
        "\n",
        "PETRUCHIO:\n",
        "I say he look'd on, if I must be content\n",
        "To stay him from the fatal of our country's bliss.\n",
        "His lordship pluck'd from this sentence then for prey,\n",
        "And then let us twain, being the moon,\n",
        "were she such a case as fills m\n",
        "</pre>\n",
        "\n",
        "While some of the sentences are grammatical, most do not make sense. The model has not learned the meaning of words, but consider:\n",
        "\n",
        "* The model is character-based. When training started, the model did not know how to spell an English word, or that words were even a unit of text.\n",
        "\n",
        "* The structure of the output resembles a play—blocks of text generally begin with a speaker name, in all capital letters similar to the dataset.\n",
        "\n",
        "* As demonstrated below, the model is trained on small batches of text (100 characters each), and is still able to generate a longer sequence of text with coherent structure."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "srXC6pLGLwS6"
      },
      "source": [
        "## Setup"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WGyKZj3bzf9p"
      },
      "source": [
        "### Import TensorFlow and other libraries"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "yG_n40gFzf9s"
      },
      "outputs": [],
      "source": [
        "import tensorflow.compat.v1 as tf\n",
        "\n",
        "\n",
        "import numpy as np\n",
        "import os\n",
        "import time"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "EHDoRoc5PKWz"
      },
      "source": [
        "### Download the Shakespeare dataset\n",
        "\n",
        "Change the following line to run this code on your own data."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "pD_55cOxLkAb"
      },
      "outputs": [],
      "source": [
        "path_to_file = tf.keras.utils.get_file('shakespeare.txt', 'https://storage.googleapis.com/download.tensorflow.org/data/shakespeare.txt')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "UHjdCjDuSvX_"
      },
      "source": [
        "### Read the data\n",
        "\n",
        "First, look in the text."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "aavnuByVymwK"
      },
      "outputs": [],
      "source": [
        "# Read, then decode for py2 compat.\n",
        "text = open(path_to_file, 'rb').read().decode(encoding='utf-8')\n",
        "# length of text is the number of characters in it\n",
        "print ('Length of text: {} characters'.format(len(text)))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Duhg9NrUymwO"
      },
      "outputs": [],
      "source": [
        "# Take a look at the first 250 characters in text\n",
        "print(text[:250])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "IlCgQBRVymwR"
      },
      "outputs": [],
      "source": [
        "# The unique characters in the file\n",
        "vocab = sorted(set(text))\n",
        "print ('{} unique characters'.format(len(vocab)))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rNnrKn_lL-IJ"
      },
      "source": [
        "## Process the text"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LFjSVAlWzf-N"
      },
      "source": [
        "### Vectorize the text\n",
        "\n",
        "Before training, we need to map strings to a numerical representation. Create two lookup tables: one mapping characters to numbers, and another for numbers to characters."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "IalZLbvOzf-F"
      },
      "outputs": [],
      "source": [
        "# Creating a mapping from unique characters to indices\n",
        "char2idx = {u:i for i, u in enumerate(vocab)}\n",
        "idx2char = np.array(vocab)\n",
        "\n",
        "text_as_int = np.array([char2idx[c] for c in text])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "tZfqhkYCymwX"
      },
      "source": [
        "Now we have an integer representation for each character. Notice that we mapped the character as indexes from 0 to `len(unique)`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "FYyNlCNXymwY"
      },
      "outputs": [],
      "source": [
        "print('{')\n",
        "for char,_ in zip(char2idx, range(20)):\n",
        "    print('  {:4s}: {:3d},'.format(repr(char), char2idx[char]))\n",
        "print('  ...\\n}')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "l1VKcQHcymwb"
      },
      "outputs": [],
      "source": [
        "# Show how the first 13 characters from the text are mapped to integers\n",
        "print ('{} ---- characters mapped to int ---- > {}'.format(repr(text[:13]), text_as_int[:13]))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bbmsf23Bymwe"
      },
      "source": [
        "### The prediction task"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wssHQ1oGymwe"
      },
      "source": [
        "Given a character, or a sequence of characters, what is the most probable next character? This is the task we're training the model to perform. The input to the model will be a sequence of characters, and we train the model to predict the output—the following character at each time step.\n",
        "\n",
        "Since RNNs maintain an internal state that depends on the previously seen elements, given all the characters computed until this moment, what is the next character?\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "hgsVvVxnymwf"
      },
      "source": [
        "### Create training examples and targets\n",
        "\n",
        "Next divide the text into example sequences. Each input sequence will contain `seq_length` characters from the text.\n",
        "\n",
        "For each input sequence, the corresponding targets contain the same length of text, except shifted one character to the right.\n",
        "\n",
        "So break the text into chunks of `seq_length+1`. For example, say `seq_length` is 4 and our text is \"Hello\". The input sequence would be \"Hell\", and the target sequence \"ello\".\n",
        "\n",
        "To do this first use the `tf.data.Dataset.from_tensor_slices` function to convert the text vector into a stream of character indices."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "0UHJDA39zf-O"
      },
      "outputs": [],
      "source": [
        "# The maximum length sentence we want for a single input in characters\n",
        "seq_length = 100\n",
        "examples_per_epoch = len(text)//seq_length\n",
        "\n",
        "# Create training examples / targets\n",
        "char_dataset = tf.data.Dataset.from_tensor_slices(text_as_int)\n",
        "\n",
        "for i in char_dataset.take(5):\n",
        "  print(idx2char[i.numpy()])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-ZSYAcQV8OGP"
      },
      "source": [
        "The `batch` method lets us easily convert these individual characters to sequences of the desired size."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "l4hkDU3i7ozi"
      },
      "outputs": [],
      "source": [
        "sequences = char_dataset.batch(seq_length+1, drop_remainder=True)\n",
        "\n",
        "for item in sequences.take(5):\n",
        "  print(repr(''.join(idx2char[item.numpy()])))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "UbLcIPBj_mWZ"
      },
      "source": [
        "For each sequence, duplicate and shift it to form the input and target text by using the `map` method to apply a simple function to each batch:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "9NGu-FkO_kYU"
      },
      "outputs": [],
      "source": [
        "def split_input_target(chunk):\n",
        "    input_text = chunk[:-1]\n",
        "    target_text = chunk[1:]\n",
        "    return input_text, target_text\n",
        "\n",
        "dataset = sequences.map(split_input_target)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "hiCopyGZymwi"
      },
      "source": [
        "Print the first examples input and target values:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "GNbw-iR0ymwj"
      },
      "outputs": [],
      "source": [
        "for input_example, target_example in  dataset.take(1):\n",
        "  print ('Input data: ', repr(''.join(idx2char[input_example.numpy()])))\n",
        "  print ('Target data:', repr(''.join(idx2char[target_example.numpy()])))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_33OHL3b84i0"
      },
      "source": [
        "Each index of these vectors are processed as one time step. For the input at time step 0, the model receives the index for \"F\" and tries to predict the index for \"i\" as the next character. At the next timestep, it does the same thing but the `RNN` considers the previous step context in addition to the current input character."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "0eBu9WZG84i0"
      },
      "outputs": [],
      "source": [
        "for i, (input_idx, target_idx) in enumerate(zip(input_example[:5], target_example[:5])):\n",
        "    print(\"Step {:4d}\".format(i))\n",
        "    print(\"  input: {} ({:s})\".format(input_idx, repr(idx2char[input_idx])))\n",
        "    print(\"  expected output: {} ({:s})\".format(target_idx, repr(idx2char[target_idx])))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MJdfPmdqzf-R"
      },
      "source": [
        "### Create training batches\n",
        "\n",
        "We used `tf.data` to split the text into manageable sequences. But before feeding this data into the model, we need to shuffle the data and pack it into batches."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "p2pGotuNzf-S"
      },
      "outputs": [],
      "source": [
        "# Batch size\n",
        "BATCH_SIZE = 64\n",
        "steps_per_epoch = examples_per_epoch//BATCH_SIZE\n",
        "\n",
        "# Buffer size to shuffle the dataset\n",
        "# (TF data is designed to work with possibly infinite sequences,\n",
        "# so it doesn't attempt to shuffle the entire sequence in memory. Instead,\n",
        "# it maintains a buffer in which it shuffles elements).\n",
        "BUFFER_SIZE = 10000\n",
        "\n",
        "dataset = dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True)\n",
        "\n",
        "dataset"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "r6oUuElIMgVx"
      },
      "source": [
        "## Build The Model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "m8gPwEjRzf-Z"
      },
      "source": [
        "Use `tf.keras.Sequential` to define the model. For this simple example three layers are used to define our model:\n",
        "\n",
        "* `tf.keras.layers.Embedding`: The input layer. A trainable lookup table that will map the numbers of each character to a vector with `embedding_dim` dimensions;\n",
        "* `tf.keras.layers.GRU`: A type of RNN with size `units=rnn_units` (You can also use a LSTM layer here.)\n",
        "* `tf.keras.layers.Dense`: The output layer, with `vocab_size` outputs."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "zHT8cLh7EAsg"
      },
      "outputs": [],
      "source": [
        "# Length of the vocabulary in chars\n",
        "vocab_size = len(vocab)\n",
        "\n",
        "# The embedding dimension\n",
        "embedding_dim = 256\n",
        "\n",
        "# Number of RNN units\n",
        "rnn_units = 1024"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "NNVB-jmMEOzP"
      },
      "source": [
        "Next define a function to build the model.\n",
        "\n",
        "Use `CuDNNGRU` if running on GPU."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "wjKZrC39ELy0"
      },
      "outputs": [],
      "source": [
        "if tf.test.is_gpu_available():\n",
        "  rnn = tf.keras.layers.CuDNNGRU\n",
        "else:\n",
        "  import functools\n",
        "  rnn = functools.partial(\n",
        "    tf.keras.layers.GRU, recurrent_activation='sigmoid')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "MtCrdfzEI2N0"
      },
      "outputs": [],
      "source": [
        "def build_model(vocab_size, embedding_dim, rnn_units, batch_size):\n",
        "  model = tf.keras.Sequential([\n",
        "    tf.keras.layers.Embedding(vocab_size, embedding_dim,\n",
        "                              batch_input_shape=[batch_size, None]),\n",
        "    rnn(rnn_units,\n",
        "        return_sequences=True,\n",
        "        recurrent_initializer='glorot_uniform',\n",
        "        stateful=True),\n",
        "    tf.keras.layers.Dense(vocab_size)\n",
        "  ])\n",
        "  return model"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "wwsrpOik5zhv"
      },
      "outputs": [],
      "source": [
        "model = build_model(\n",
        "  vocab_size = len(vocab),\n",
        "  embedding_dim=embedding_dim,\n",
        "  rnn_units=rnn_units,\n",
        "  batch_size=BATCH_SIZE)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RkA5upJIJ7W7"
      },
      "source": [
        "For each character the model looks up the embedding, runs the GRU one timestep with the embedding as input, and applies the dense layer to generate logits predicting the log-likelihood of the next character:\n",
        "\n",
        "![A drawing of the data passing through the model](https://tensorflow.org/r1/tutorials/sequences/images/text_generation_training.png)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-ubPo0_9Prjb"
      },
      "source": [
        "## Try the model\n",
        "\n",
        "Now run the model to see that it behaves as expected.\n",
        "\n",
        "First check the shape of the output:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "C-_70kKAPrPU"
      },
      "outputs": [],
      "source": [
        "for input_example_batch, target_example_batch in dataset.take(1):\n",
        "  example_batch_predictions = model(input_example_batch)\n",
        "  print(example_batch_predictions.shape, \"# (batch_size, sequence_length, vocab_size)\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Q6NzLBi4VM4o"
      },
      "source": [
        "In the above example the sequence length of the input is `100` but the model can be run on inputs of any length:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "vPGmAAXmVLGC"
      },
      "outputs": [],
      "source": [
        "model.summary()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "uwv0gEkURfx1"
      },
      "source": [
        "To get actual predictions from the model we need to sample from the output distribution, to get actual character indices. This distribution is defined by the logits over the character vocabulary.\n",
        "\n",
        "Note: It is important to _sample_ from this distribution as taking the _argmax_ of the distribution can easily get the model stuck in a loop.\n",
        "\n",
        "Try it for the first example in the batch:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4V4MfFg0RQJg"
      },
      "outputs": [],
      "source": [
        "sampled_indices = tf.random.categorical(example_batch_predictions[0], num_samples=1)\n",
        "sampled_indices = tf.squeeze(sampled_indices,axis=-1).numpy()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "QM1Vbxs_URw5"
      },
      "source": [
        "This gives us, at each timestep, a prediction of the next character index:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "YqFMUQc_UFgM"
      },
      "outputs": [],
      "source": [
        "sampled_indices"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LfLtsP3mUhCG"
      },
      "source": [
        "Decode these to see the text predicted by this untrained model:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "xWcFwPwLSo05"
      },
      "outputs": [],
      "source": [
        "print(\"Input: \\n\", repr(\"\".join(idx2char[input_example_batch[0]])))\n",
        "print()\n",
        "print(\"Next Char Predictions: \\n\", repr(\"\".join(idx2char[sampled_indices ])))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LJL0Q0YPY6Ee"
      },
      "source": [
        "## Train the model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "YCbHQHiaa4Ic"
      },
      "source": [
        "At this point the problem can be treated as a standard classification problem. Given the previous RNN state, and the input this time step, predict the class of the next character."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "trpqTWyvk0nr"
      },
      "source": [
        "### Attach an optimizer, and a loss function"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "UAjbjY03eiQ4"
      },
      "source": [
        "The standard `tf.keras.losses.sparse_categorical_crossentropy` loss function works in this case because it is applied across the last dimension of the predictions.\n",
        "\n",
        "Because our model returns logits, we need to set the `from_logits` flag.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4HrXTACTdzY-"
      },
      "outputs": [],
      "source": [
        "def loss(labels, logits):\n",
        "  return tf.keras.losses.sparse_categorical_crossentropy(labels, logits, from_logits=True)\n",
        "\n",
        "example_batch_loss  = loss(target_example_batch, example_batch_predictions)\n",
        "print(\"Prediction shape: \", example_batch_predictions.shape, \" # (batch_size, sequence_length, vocab_size)\")\n",
        "print(\"scalar_loss:      \", example_batch_loss.numpy().mean())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jeOXriLcymww"
      },
      "source": [
        "Configure the training procedure using the `tf.keras.Model.compile` method. We'll use `tf.train.AdamOptimizer` with default arguments and the loss function."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "DDl1_Een6rL0"
      },
      "outputs": [],
      "source": [
        "model.compile(\n",
        "    optimizer = tf.train.AdamOptimizer(),\n",
        "    loss = loss)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ieSJdchZggUj"
      },
      "source": [
        "### Configure checkpoints"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "C6XBUUavgF56"
      },
      "source": [
        "Use a `tf.keras.callbacks.ModelCheckpoint` to ensure that checkpoints are saved during training:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "W6fWTriUZP-n"
      },
      "outputs": [],
      "source": [
        "# Directory where the checkpoints will be saved\n",
        "checkpoint_dir = './training_checkpoints'\n",
        "# Name of the checkpoint files\n",
        "checkpoint_prefix = os.path.join(checkpoint_dir, \"ckpt_{epoch}\")\n",
        "\n",
        "checkpoint_callback=tf.keras.callbacks.ModelCheckpoint(\n",
        "    filepath=checkpoint_prefix,\n",
        "    save_weights_only=True)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "3Ky3F_BhgkTW"
      },
      "source": [
        "### Execute the training"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "IxdOA-rgyGvs"
      },
      "source": [
        "To keep training time reasonable, use 3 epochs to train the model. In Colab, set the runtime to GPU for faster training."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "7yGBE2zxMMHs"
      },
      "outputs": [],
      "source": [
        "EPOCHS=3"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "UK-hmKjYVoll"
      },
      "outputs": [],
      "source": [
        "history = model.fit(dataset.repeat(), epochs=EPOCHS, steps_per_epoch=steps_per_epoch, callbacks=[checkpoint_callback])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "kKkD5M6eoSiN"
      },
      "source": [
        "## Generate text"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "JIPcXllKjkdr"
      },
      "source": [
        "### Restore the latest checkpoint"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LyeYRiuVjodY"
      },
      "source": [
        "To keep this prediction step simple, use a batch size of 1.\n",
        "\n",
        "Because of the way the RNN state is passed from timestep to timestep, the model only accepts a fixed batch size once built.\n",
        "\n",
        "To run the model with a different `batch_size`, we need to rebuild the model and restore the weights from the checkpoint.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "zk2WJ2-XjkGz"
      },
      "outputs": [],
      "source": [
        "tf.train.latest_checkpoint(checkpoint_dir)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "LycQ-ot_jjyu"
      },
      "outputs": [],
      "source": [
        "model = build_model(vocab_size, embedding_dim, rnn_units, batch_size=1)\n",
        "\n",
        "model.load_weights(tf.train.latest_checkpoint(checkpoint_dir))\n",
        "\n",
        "model.build(tf.TensorShape([1, None]))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "71xa6jnYVrAN"
      },
      "outputs": [],
      "source": [
        "model.summary()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "DjGz1tDkzf-u"
      },
      "source": [
        "### The prediction loop\n",
        "\n",
        "The following code block generates the text:\n",
        "\n",
        "* It starts by choosing a start string, initializing the RNN state and setting the number of characters to generate.\n",
        "\n",
        "* Get the prediction distribution of the next character using the start string and the RNN state.\n",
        "\n",
        "* Use a multinomial distribution to calculate the index of the predicted character. Use this predicted character as our next input to the model.\n",
        "\n",
        "* The RNN state returned by the model is fed back into the model so that it now has more context, instead of only one word. After predicting the next word, the modified RNN states are again fed back into the model, which is how it learns as it gets more context from the previously predicted words.\n",
        "\n",
        "\n",
        "![To generate text the model's output is fed back to the input](https://tensorflow.org/r1/tutorials/sequences/images/text_generation_sampling.png)\n",
        "\n",
        "Looking at the generated text, you'll see the model knows when to capitalize and make paragraphs, and it imitates a Shakespeare-like writing vocabulary. With the small number of training epochs, it has not yet learned to form coherent sentences."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "WvuwZBX5Ogfd"
      },
      "outputs": [],
      "source": [
        "def generate_text(model, start_string):\n",
        "  # Evaluation step (generating text using the learned model)\n",
        "\n",
        "  # Number of characters to generate\n",
        "  num_generate = 1000\n",
        "\n",
        "  # Converting our start string to numbers (vectorizing)\n",
        "  input_eval = [char2idx[s] for s in start_string]\n",
        "  input_eval = tf.expand_dims(input_eval, 0)\n",
        "\n",
        "  # Empty string to store our results\n",
        "  text_generated = []\n",
        "\n",
        "  # Low temperatures results in more predictable text.\n",
        "  # Higher temperatures results in more surprising text.\n",
        "  # Experiment to find the best setting.\n",
        "  temperature = 1.0\n",
        "\n",
        "  # Here batch size == 1\n",
        "  model.reset_states()\n",
        "  for i in range(num_generate):\n",
        "      predictions = model(input_eval)\n",
        "      # remove the batch dimension\n",
        "      predictions = tf.squeeze(predictions, 0)\n",
        "\n",
        "      # using a multinomial distribution to predict the word returned by the model\n",
        "      predictions = predictions / temperature\n",
        "      predicted_id = tf.multinomial(predictions, num_samples=1)[-1,0].numpy()\n",
        "\n",
        "      # We pass the predicted word as the next input to the model\n",
        "      # along with the previous hidden state\n",
        "      input_eval = tf.expand_dims([predicted_id], 0)\n",
        "\n",
        "      text_generated.append(idx2char[predicted_id])\n",
        "\n",
        "  return (start_string + ''.join(text_generated))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ktovv0RFhrkn"
      },
      "outputs": [],
      "source": [
        "print(generate_text(model, start_string=u\"ROMEO: \"))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "AM2Uma_-yVIq"
      },
      "source": [
        "The easiest thing you can do to improve the results it to train it for longer (try `EPOCHS=30`).\n",
        "\n",
        "You can also experiment with a different start string, or try adding another RNN layer to improve the model's accuracy, or adjusting the temperature parameter to generate more or less random predictions."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Y4QwTjAM6A2O"
      },
      "source": [
        "## Advanced: Customized Training\n",
        "\n",
        "The above training procedure is simple, but does not give you much control.\n",
        "\n",
        "So now that you've seen how to run the model manually let's unpack the training loop, and implement it ourselves. This gives a starting point, for example, to implement _curriculum learning_ to help stabilize the model's open-loop output.\n",
        "\n",
        "We will use `tf.GradientTape` to track the gradients. You can learn more about this approach by reading the [eager execution guide](https://www.tensorflow.org/r1/guide/eager).\n",
        "\n",
        "The procedure works as follows:\n",
        "\n",
        "* First, initialize the RNN state. We do this by calling the `tf.keras.Model.reset_states` method.\n",
        "\n",
        "* Next, iterate over the dataset (batch by batch) and calculate the *predictions* associated with each.\n",
        "\n",
        "* Open a `tf.GradientTape`, and calculate the predictions and loss in that context.\n",
        "\n",
        "* Calculate the gradients of the loss with respect to the model variables using the `tf.GradientTape.grads` method.\n",
        "\n",
        "* Finally, take a step downwards by using the optimizer's `tf.train.Optimizer.apply_gradients` method.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "_XAm7eCoKULT"
      },
      "outputs": [],
      "source": [
        "model = build_model(\n",
        "  vocab_size = len(vocab),\n",
        "  embedding_dim=embedding_dim,\n",
        "  rnn_units=rnn_units,\n",
        "  batch_size=BATCH_SIZE)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "qUKhnZtMVpoJ"
      },
      "outputs": [],
      "source": [
        "optimizer = tf.train.AdamOptimizer()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "d4tSNwymzf-q"
      },
      "outputs": [],
      "source": [
        "# Training step\n",
        "EPOCHS = 1\n",
        "\n",
        "for epoch in range(EPOCHS):\n",
        "    start = time.time()\n",
        "\n",
        "    # initializing the hidden state at the start of every epoch\n",
        "    # initially hidden is None\n",
        "    hidden = model.reset_states()\n",
        "\n",
        "    for (batch_n, (inp, target)) in enumerate(dataset):\n",
        "          with tf.GradientTape() as tape:\n",
        "              # feeding the hidden state back into the model\n",
        "              # This is the interesting step\n",
        "              predictions = model(inp)\n",
        "              loss = tf.losses.sparse_softmax_cross_entropy(target, predictions)\n",
        "\n",
        "          grads = tape.gradient(loss, model.trainable_variables)\n",
        "          optimizer.apply_gradients(zip(grads, model.trainable_variables))\n",
        "\n",
        "          if batch_n % 100 == 0:\n",
        "              template = 'Epoch {} Batch {} Loss {:.4f}'\n",
        "              print(template.format(epoch+1, batch_n, loss))\n",
        "\n",
        "    # saving (checkpoint) the model every 5 epochs\n",
        "    if (epoch + 1) % 5 == 0:\n",
        "      model.save_weights(checkpoint_prefix.format(epoch=epoch))\n",
        "\n",
        "    print ('Epoch {} Loss {:.4f}'.format(epoch+1, loss))\n",
        "    print ('Time taken for 1 epoch {} sec\\n'.format(time.time() - start))\n",
        "\n",
        "model.save_weights(checkpoint_prefix.format(epoch=epoch))"
      ]
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "collapsed_sections": [],
      "name": "text_generation.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
